﻿using Client.HttpHelp;
using Client.ICommandNotify;
using Client.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;

namespace Client.ViewModel
{
    public class BillNoAuditAfterModel : NotifyBase
    {
        private readonly Http http;
        private readonly MessageDialog.Dialog dialog;
        private readonly SqlServer.DbContext dbContext;
        Models.Http.ParameterModel parameterModel = new Models.Http.ParameterModel();
        private Dictionary<string, string> uri = new Dictionary<string, string>()
        {
            { "SRBG_Project", "http://cpms_Project.scrbg.com/json.rpc"},
            {"SRBG_Equip", "http://cpms_equip.scrbg.com/json.rpc"},
            { "SRBG_Revolve", "http://cpms_revolve.scrbg.com/json.rpc" },
            { "SRBG_Tender", "http://cpms_tender.scrbg.com/json.rpc"},
            { "SRBG_Material", "http://cpms_material.scrbg.com/json.rpc"}

        };
        private string? objmodel { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public BillNoAuditAfterModel()
        {
            http = HelpTools.IOC.Getobject<Http>();
            dialog = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            dbContext = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            Selectcommand = new Command(ReverseDoExecute, ReverseCanExecute);
            AddModularListCommand = new Command(AddModularListCommandMethodDoExecute, AddModularListCommandMethodCanExecute);
            TypeCommand = new Command(TypeCommandDoExecute, TypeCommandCanExecute);
            FlowCommand = new Command(FlowCommandDoExecute, FlowCommandCanExecute);
        }


        #region 命令
        public Command Selectcommand { get; set; }
        //
        public Command AddModularListCommand { get; set; }
        public Command TypeCommand { get; set; }

        public Command FlowCommand {  get; set; }
        #endregion
        #region 方法
        /// <summary>
        /// 处理流程报错方法
        /// </summary>
        /// <param name="obj"></param>
        private void FlowCommandDoExecute(object obj)
        {
            // 正则表达式模式
            dbContext.SqlConfigstr = $"Data Source=192.168.100.6;Initial Catalog={SelectModular};User ID=sa;Password=asdw@122";
            DataTable data=new DataTable() ;
            if (BillNo.Contains('-') && BillNo.Split('-').Length==5)
            {
                data = dbContext.Where($"SELECT * FROM [dbo].[{SelectType}] WHERE BillId='{BillNo}'");//查询单据
                
            }
            else
            {
                data = dbContext.Where($"SELECT * FROM [dbo].[{SelectType}] WHERE BillNo='{BillNo}'");//查询单据
            }
            if (data.Rows.Count == 0)
            {
                WPFDevelopers.Minimal.Controls.MessageBox.Show("操作失败,没有查询到数据", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            dbContext.SqlConfigstr = "Data Source=192.168.100.150;Initial Catalog=SRBG_FlowEngin;User ID=sa;Password=sclq@pcwp1.0;max pool size=1024";
            var data4 = dbContext.Where($"SELECT A.DISPID, B.TASKTYPE, C.UNITINDEX, C.UNITNAME, A.USERNAME, B.WORKID, A.STATE,B.STATE AS TASKSTATE,A.NOTIFYTIME, A.FINISHTIME, B.TASKID, E.PRIORTASKID, A.ISPASS " +
                                        $"FROM USERDISP A WITH(NOLOCK) INNER JOIN TASK B WITH(NOLOCK) ON A.TASKID = B.TASKID INNER JOIN UNIT C WITH(NOLOCK) ON B.UNITID = C.UNITID INNER JOIN WORK D WITH(NOLOCK) ON B.WORKID = D.WORKID LEFT " +
                                        $"JOIN TASKORDER E ON B.TASKID = E.NEXTTASKID WHERE D.STATE <> 2 AND " +
                                        $"D.WORKID = '{data.Rows[0]["WorkId"]}' ORDER BY E.PRIORTASKID");
            var lastdata= data4.AsEnumerable().Last();
            if(lastdata != null && lastdata["TASKSTATE"].ToString() == "1")
            {
              var da= data4.AsEnumerable().Where(o => o["TASKID"].ToString()== lastdata["PRIORTASKID"].ToString());
               if(da.Count() > 0)
                {
                    if (da.AsEnumerable()?.FirstOrDefault()?["TASKSTATE"]?.ToString()=="1")
                    {
                        dbContext.Update($"update TASK set STATE = 2,FINISHTIME = GETDATE()  where TASKID = '{da.AsEnumerable()?.FirstOrDefault()?["TASKID"]}'");
                        if (da.AsEnumerable()?.FirstOrDefault()?["STATE"]?.ToString() == "1")
                        {
                         dbContext.Update($"update USERDISP set STATE = 2,FINISHTIME = GETDATE(),ISPASS = 1  where DISPID = '{da.AsEnumerable()?.FirstOrDefault()?["DISPID"]}'");
                        }
                        WPFDevelopers.Minimal.Controls.MessageBox.Show("处理成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
        }
        private bool FlowCommandCanExecute()
        {
            return string.IsNullOrWhiteSpace(BillNo) == false&&string.IsNullOrWhiteSpace(SelectModular)==false && string.IsNullOrWhiteSpace(SelectType) == false;
        }
        /// <summary>
        /// 判断按钮是否可用
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private bool ReverseCanExecute()
        {
            return string.IsNullOrWhiteSpace(BillNo) == false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        private async void ReverseDoExecute(object obj)
        {
            dialog.OpenDialog = true;
            await Task.Run(() =>
            {
                if (string.IsNullOrWhiteSpace(objmodel) || uri.ContainsKey(SelectModular) == false) return;
                if (AuditAfterconfigurationList.Where(o => string.IsNullOrWhiteSpace(o.Value)).Any()) return;
                foreach (var item in AuditAfterconfigurationList)
                {
                    objmodel = objmodel.Replace("?" + item.ParamsName + "?", item.Value);
                }
                http.Uir = uri[SelectModular];
                parameterModel.@params = Newtonsoft.Json.JsonConvert.DeserializeObject(objmodel);
            });
            ResponseData= await http.PostData(parameterModel, "", "application/json");
            dialog.OpenDialog = false;
        }
        private bool TypeCommandCanExecute()
        {
            return true;
        }

        private void TypeCommandDoExecute(object obj)
        {
          var data=   dbContext.Where($"SELECT * FROM AuditAfterconfiguration WHERE Type='{SelectType}'").Select().Select(o =>
            {
                return new
                {
                    method=o["method"]?.ToString(),
                    Id = Convert.ToInt16(o["Id"]),
                    @params=o["params"]?.ToString(),
                };
            }).FirstOrDefault();
            parameterModel.method=data?.method;
            objmodel = data?.@params;
            AuditAfterconfigurationList = dbContext.Where($"SELECT * FROM [dbo].[AuditAfterconfigurationSubsidiary] WHERE [foreignkey] = '{data?.Id}'").Select().Select(o =>
            {
                return new fterconfiguration
                {
                    ParamsName = o["FieldName"]?.ToString()
                };
            }).ToList();
            if (AuditAfterconfigurationList.Count>=1)
            {
                Iscan = true;
            }
            else
            {
                Iscan = false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private async void AddModularListCommandMethodDoExecute(object obj)
        {
            if (TypeList_ != null && TypeList_.Count > 0)
                TypeList_.Clear();
            dbContext.SqlConfigstr = "Server=192.168.100.84;Database=PCWP_OperationHelper;uid=sa;pwd=asdw@123";
            var Listdata = await Task.Run(() =>
            {
                return dbContext.Where($"SELECT  a.DatabaseNameValue,a.DataSheet,a.DataSheetValue FROM DataBasekey a WHERE DatabaseNameValue='{SelectModular}'").Select().Select(o =>
                {
                    return new
                    {
                        DatabaseNameValue = o["DatabaseNameValue"].ToString(),
                        DataSheetValue = o["DataSheetValue"].ToString(),
                        DataSheet = o["DataSheet"].ToString()
                    };
                });
            });
            foreach (var item in Listdata)
            {
                if (item.DataSheet != null && item.DataSheetValue != null)
                {

                    if (!TypeList_.ContainsKey(item.DataSheetValue))
                        TypeList_?.Add(item.DataSheetValue, item.DataSheet);
                }
            }

        }
        private bool AddModularListCommandMethodCanExecute()
        {
            return true;
        }
        #endregion

        #region 属性
        private bool Iscan_;

        public bool Iscan
        {
            get { return Iscan_; }
            set {
                Iscan_ = value;
                SetProperty(ref Iscan_, Iscan_);
            }
        }

        private string ResponseData_;

        public string ResponseData
        {
            get { return ResponseData_; }
            set
            {
                ResponseData_ = value;
                SetProperty(ref ResponseData_, ResponseData);
            }
        }
        private Dictionary<string, string> ModularList_;
        /// <summary>
        /// 模块
        /// </summary>
        public Dictionary<string, string> ModularList
        {
            get
            {
                if (ModularList_ == null)
                {
                    ModularList_ = new Dictionary<string, string>();
                    ModularList_.Add("SRBG_Project", "工程");
                    ModularList_.Add("SRBG_Equip", "设备");
                    ModularList_.Add("SRBG_Revolve", "周财");
                    ModularList_.Add("SRBG_Tender", "招标");
                    ModularList_.Add("SRBG_Material", "物资");
                    ModularList_.Add("SRBG_CBM", "合同");
                }
                return ModularList_;
            }
            set
            {
                ModularList_ = value;
                SetProperty(ref ModularList_, ModularList);
            }
        }

        private ObservableDictionary<string, string> TypeList_;
        /// <summary>
        /// 模块类型
        /// </summary>
        public ObservableDictionary<string, string> TypeList
        {
            get
            {
                if (TypeList_ == null)
                {
                    TypeList_ = new ObservableDictionary<string, string>();


                }
                return TypeList_;
            }
            set
            {
                TypeList_ = value;
                SetProperty(ref TypeList_, TypeList);
            }
        }

        private string SelectModular_;
        /// <summary>
        /// 选择的模块
        /// </summary>
        public string SelectModular
        {
            get
            {
                return SelectModular_;
            }
            set { SelectModular_ = value; }
        }
        private string SelectType_;
        /// <summary>
        /// 选择模块类型
        /// </summary>
        public string SelectType
        {
            get { return SelectType_; }
            set { SelectType_ = value; }
        }
        private string BillNo_;
        /// <summary>
        /// 单据编号
        /// </summary>
        public string BillNo
        {
            get { return BillNo_; }
            set { BillNo_ = value; }
        }
        private List<fterconfiguration> AuditAfterconfigurationList_;

        public List<fterconfiguration> AuditAfterconfigurationList
        {
            get { return AuditAfterconfigurationList_; }
            set { AuditAfterconfigurationList_ = value;
                SetProperty(ref AuditAfterconfigurationList_, AuditAfterconfigurationList);
            }
        }

        #endregion
    }
}
